package com.ifinc.common.socket.parser;

import com.alibaba.fastjson.JSON;
import com.ifinc.common.socket.model.SckRequest;
import com.ifinc.common.socket.model.SocketExecutor;
import com.ifinc.common.socket.impl.SckResponseNotFound;
import com.ifinc.common.utils.Bytes;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: luotao
 * Date: 12-5-29
 * Time: 18:50
 */
public class JsonDispatcher implements ApplicationContextAware, InitializingBean {

    private static final SckResponseNotFound NOT_FOUND = new SckResponseNotFound();

    ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    private Map<Integer, SocketExecutor> commandMap = new HashMap<Integer, SocketExecutor>();


    public void setCommandMap(Map<Integer, SocketExecutor> commandMap) {
        this.commandMap = commandMap;
    }

    private Map<Integer, Class> requestClassMap = new HashMap<Integer, Class>();

    public void setRequestMap(Map<Integer, SckRequest> requestMap) {
        for (Map.Entry<Integer, SckRequest> requestEntry : requestMap.entrySet()) {
            requestClassMap.put(requestEntry.getValue().getCommand(),requestEntry.getValue().getClass());
        }
       // this.requestMap = requestMap;
    }

    public <Out> String doDispatch(byte[] src) {
        int command = Bytes.toInt(src, 0, 4);


        byte[] json = new byte[src.length - 4];
        System.arraycopy(src, 4, json, 0, json.length);

        String src_str = new String(json);
        String uuid = src_str.substring(0,36);
        String str_json = src_str.substring(36);
        System.out.println("str_json = " + str_json);
        Class<SckRequest> clz_request = requestClassMap.get(command);
        SckRequest request = JSON.parseObject(str_json, clz_request);

        Object serviceObject = commandMap.get(command);
        if (serviceObject == null || !(serviceObject instanceof SocketExecutor)) {
            return JSON.toJSONString(NOT_FOUND);
        }
        SocketExecutor<SckRequest, Out> executor = (SocketExecutor<SckRequest, Out>) serviceObject;
        String result = "";
        try {
            Out out = executor.execute(request);
            result = JSON.toJSONString(out);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        result = uuid+result;
        return result;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
    }
}
